package com.fun.feifun.base.utils;

import com.fun.feifun.modules.sys.auth.model.dto.MenuTree;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 树状图
 * @author wukefei
 * @date $ $
 */
public class TreeUtil {

    /**
     * 修改后的方式
     */
    public static List<MenuTree> listToTree(List<MenuTree> srcList) {
        if(CollectionUtils.isEmpty(srcList)){
            return null;
        }
        List<MenuTree> resultList = new ArrayList<>();
        Map<Long, List<MenuTree>> pidMap = srcList.stream()
                .collect(Collectors.groupingBy(MenuTree::getParentId, Collectors.toList()));
        resultList.add(srcList.get(0));
        setChildren(srcList.get(0), pidMap);
        return resultList;
    }

    public static void setChildren(MenuTree dto, Map<Long, List<MenuTree>> pidMap) {
        List<MenuTree> childrenList = pidMap.get(dto.getId());
        if (childrenList == null || childrenList.isEmpty()) {
            dto.setChild(Collections.EMPTY_LIST);
            return;
        }
        childrenList.sort((a,b)->Integer.compare(a.getSort(),b.getSort()));
        dto.setChild(childrenList);
        for (MenuTree child : childrenList) {
            setChildren(child, pidMap);
        }
    }

}
